package cn.codeforfun.user.controller;

import cn.codeforfun.common.model.User;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.util.List;

/**
 * Created by wangbin on 2016/8/5.
 */
public class UserController extends Controller {

    @Before(CacheInterceptor.class)
    @CacheName("userList")
    public void list() {
        List<User> users = User.dao.find("select * from user");
        setAttr("data", users);
        renderJson();
    }

    public void get() {
        Integer id = getParaToInt("id");
        User user = User.dao.findById(id);
        setAttr("data", user);
        renderJson();
    }

    @Before(EvictInterceptor.class)
    @CacheName("userList")
    public void save() {
        String name = getPara("name");
        if (name == null) {
            renderJson();
            return;
        }
        User user = new User();
        user.setName(name);
        user.save();
        setAttr("data", user);
        renderJson();
    }

    @Before(EvictInterceptor.class)
    @CacheName("userList")
    public void delete() {
        Integer id = getParaToInt("id");
        User.dao.deleteById(id);
        setAttr("data", id);
        renderJson();
    }
}
